package com.sjy.project.fym.api;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.sjy.common.result.BaseResponse;
import com.sjy.common.utils.StringUtils;
import com.sjy.common.utils.file.FileUploadUtils;
import com.sjy.common.utils.file.FileUtils;
import com.sjy.framework.config.ServerConfig;
import com.sjy.framework.config.SjyConfig;
import com.sjy.framework.web.domain.AjaxResult;
import com.sjy.project.fym.place.domain.FyPlace;
import com.sjy.project.system.dict.domain.DictData;
import com.sjy.project.system.dict.service.IDictDataService;

@RestController
@Api(value = "通用接口", description = "经开区防疫相关接口", tags = {"经开区防疫"})
@RequestMapping({"/api/fym/common"})
public class ApiCommonController {
  private static final Logger log = LoggerFactory.getLogger(ApiCommonController.class);
  
  @Autowired
  private ServerConfig serverConfig;

  @Autowired
  private IDictDataService dictDataService;
  
  @GetMapping({"/download"})
  @ApiOperation(value = "1001、文件下载", position = 1001)
  public void fileDownload(String fileName,@RequestParam(required = false,defaultValue = "false") Boolean delete, HttpServletResponse response, HttpServletRequest request) {
	  try
      {
          if (!FileUtils.checkAllowDownload(fileName))
          {
              throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
          }
          String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
          String filePath = SjyConfig.getDownloadPath() + fileName;
          //D:/zfw/uploadPath/download//profile/upload/2021/05/18/1582beba-4ef0-49b9-ba07-0c429c2d8944.jpg
          //filePath = "D:\\zfw\\uploadPath\\upload\\2021\\05\\18\\1582beba-4ef0-49b9-ba07-0c429c2d8944.jpg";
          if(filePath.contains("/download//profile/upload/")) {
        	  filePath = filePath.replace("/download//profile/upload/", "/upload/");
          }

          response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
          FileUtils.setAttachmentResponseHeader(response, realFileName);
          FileUtils.writeBytes(filePath, response.getOutputStream());
          if (delete)
          {
              FileUtils.deleteFile(filePath);
          }
      }
      catch (Exception e)
      {
          log.error("下载文件失败", e);
      }
  }
  
  @PostMapping({"/upload"})
  @ApiOperation(value = "1002、文件上传", position = 1002)
  @ApiImplicitParams({
      @ApiImplicitParam(required=false,name="file",dataType = "",value="文件",example="1")
  })
  public AjaxResult uploadFile(MultipartFile file) throws Exception {
    try {
    	String filePath = SjyConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        String url = serverConfig.getUrl() + fileName;
        AjaxResult ajax = AjaxResult.success();
        ajax.put("fileName", fileName);
        ajax.put("url", url);
        return ajax;
    } catch (Exception e) {
      return AjaxResult.error(e.getMessage());
    } 
  }
  
  @PostMapping({"/upload2"})
  @ApiOperation(value = "1002.2、文件上传", position = 1002)
  @ApiImplicitParams({
      @ApiImplicitParam(required=false,name="file",dataType = "",value="文件",example="1")
  })
  public ResponseEntity<BaseResponse> upload2(MultipartFile file) throws Exception {
    try {
    	String filePath = SjyConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        String url = serverConfig.getUrl() + fileName;
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("fileName", fileName);
        map.put("url", url);
        return BaseResponse.generateOKResponseEntity("上传成功",map); 
    } catch (Exception e) {
    	return BaseResponse.generateBadResponseEntity("上传失败", e.getMessage());
    } 
  }
  
  @GetMapping({"/download/resource"})
  public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {
      if (!FileUtils.checkAllowDownload(resource)) {
    	  throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", new Object[] { resource })); 
      }
      String localPath = SjyConfig.getUploadPath();
      String downloadPath = String.valueOf(localPath) + StringUtils.substringAfter(resource, "/profile");
      String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
      response.setContentType("application/octet-stream");
      FileUtils.setAttachmentResponseHeader(response, downloadName);
      FileUtils.writeBytes(downloadPath, (OutputStream)response.getOutputStream());
    } catch (Exception e) {
      log.error("下载文件失败", e);
    } 
  }
  
  
  @ApiOperation(value = "1001、获取数据字典内容", position = 1001, notes = "	fym_goods_type;fym_good_apply_status")
  @ApiImplicitParams({
	  @ApiImplicitParam(name = "dictType", value = "字典类型", required = false, example = "1"),
	  @ApiImplicitParam(name = "dictValue", value = "字典键值", required = false, example = "1"),
	  @ApiImplicitParam(name = "dictLabel", value = "字典标签", required = false, example = "1"),
  })
  @PostMapping({"/getDictData"})
  public ResponseEntity<BaseResponse<List<DictData>>> getDictData(@ApiIgnore DictData dictData)
  { 
  	List<DictData> list = dictDataService.selectDictDataList(dictData);
  	if(list!=null&&list.size()>0) {
  		return BaseResponse.generateOKResponseEntity(list);
  	}
  	return BaseResponse.generateBadResponseEntity(500,"获取数据字典失败", list);
  	
  }
}
